package cn.itcast.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 登录拦截
 * @author 虎哥
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求上下文，就是请求进入Zuul到返回给用户之前各个过滤器共享的域对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取Request
        HttpServletRequest request = ctx.getRequest();
        // 获取请求参数中的： access-token
        String token = request.getParameter("access-token");
        // 判断值是否为admin
        if (!"admin".equalsIgnoreCase(token)) {
            // 否：拦截. 参数是true，就放行；是false，就拦截
            ctx.setSendZuulResponse(false);
            // 设置返回的状态码为401，代表unauthorized，未授权
            ctx.setResponseStatusCode(401);
        }
        // 是：放行，什么都不做就是放行
        return null;
    }
}
